package algorithm_demo.demo01;

import java.util.Arrays;

/**
 * 二分查找
 * 查找
 * <p>
 * 二分法
 * 1. 有序数组中找到num
 * 2. 有序数组中找到>=num最左的位置
 * 3. 有序数组中找到<=num最右的位置
 * 4. 局部最小值问题
 *
 * @author Api
 * @date 2023/1/27 1:45
 */
public class Code11_BinarySearch {

    /*查找某个数组，返回其下标*/
    /*暴力法，时间复杂度O(N)*/
    public static int findNum(int[] arr, int num){
        for(int i = 0; i < arr.length; i++){
            if (arr[i] == num){
                return i;
            }
        }
        return -1;
    }


    public static int binaryFindNum(int[] arr, int L, int R, int num){
        if (L > R){//递归结束
            return -1;
        }
        int mid = (L + R )>>1;
        int minVal = arr[mid];
        if (num > minVal){
            return binaryFindNum(arr, mid + 1, R, num);//向右递归
        }else if (num < minVal){
            return binaryFindNum(arr, L, mid -1, num);//向左递归
        }else{
            return mid;
        }
    }


    //1. 有序数组中找到num,时间复杂度为O(log2N)
    //保证arr有序
    public static boolean find(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        int L = 0;
        int R = arr.length - 1;
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] == num) {
                return true;
            } else if (arr[mid] < num) {
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return false;
    }

    public static boolean test(int[] sortArr, int num) {
        for (int cur : sortArr) {
            if (cur == num) {
                return true;
            }
        }
        return false;
    }

    //生成随机数组（对数器, 随机等概率事件）
    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)((maxValue+1)*Math.random())-(int)((maxValue)*Math.random());
        }
        return arr;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (test(arr, value) != find(arr, value)) {
                System.out.println("出错了！");
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }


}
